The TSstudio provides a set of tools for time series analysis and forecasting application. The following document demonstrates the usage of the package to forecast the monthly consumption of natural gas in the US in the next 5 years (or 60 months)

Installation

Install from CRAN:

install.packages("TSstudio")

Or from Github:

devtools::install_github("RamiKrispin/TSstudio")

As for December 2018, the most updated version is 0.1.3:

library(TSstudio)
packageVersion("TSstudio")
## [1] '0.1.3.9000'

Data

The USgas dataset, one of the package datasets, represents the monthly consumption (in Billion Cubic Feet) of natural gas in the US since January 2000 [1]:

# Load the series
data("USgas")

# Get the series info
ts_info(USgas)
##  The USgas series is a ts object with 1 variable and 227 observations
##  Frequency: 12 
##  Start time: 2000 1 
##  End time: 2018 11
# Plot the series
ts_plot(USgas,
        title = "US Monthly Natural Gas Consumption",
        Ytitle = "Billion Cubic Feet",
        Xtitle = "Source: Federal Reserve Bank of St. Louis", 
        slider = TRUE)

Seasonal analysis

You can note from the plot above that the series has strong seasonality and fairly stable trend (or growth). We will use the ts_seasonal and the ts_heatmap the explore further the seasonality and trend of the series:

ts_seasonal(USgas, type = "all")

The ts_seasonal function provides three different views of the seasonality of the series (when the type argument is equal to "all"):

The combination of the three plots provides the full picture on the series seaosnality. Alternativliy, you can use the ts_heatmap to get a time series heatmap represenative of the series:

ts_heatmap(USgas)

Correlation analysis

The next step is to identify the level of correlation between the series and it’s lags, using the ts_acf function, which is nothing but an interactive version of the acf function:

ts_acf(USgas, lag.max = 36)

As expected you can notice that the series is highely correlated with it’s seasonal lags. A more intuative way to review identify a deoandency between the series and its lags is with the ts_lags function, which provides plots of the series against its lags:

ts_lags(USgas)

As observed before with the ts_acf function, you can notice that the seasonal lag (or lag 12) of the series has a strong linear relationship with the series. In a semilar way we can zoom in on the seasonal lags of the series using the lags argument:

ts_lags(USgas, lags = c(12, 24, 36, 48))

Forecasting the series

Using the information we learned from the seasonal and correlation analysis, we will conduct “horse race” between several models and select the one that performe best on the testing set, by using two training approaches:

Traditional Approach

# Set the sample out and forecast horizon
h1 <- 12 # sample out lenght
h2 <- 60 # forecast horizon

USgas_split <- ts_split(USgas, sample.out = h1)
train <- USgas_split$train
test <- USgas_split$test

ts_info(train)
##  The train series is a ts object with 1 variable and 215 observations
##  Frequency: 12 
##  Start time: 2000 1 
##  End time: 2017 11
ts_info(test)
##  The test series is a ts object with 1 variable and 12 observations
##  Frequency: 12 
##  Start time: 2017 12 
##  End time: 2018 11
set.seed(1234)

library(forecast)

# auto.arima
md1 <- auto.arima(train, 
                  stepwise = FALSE, 
                  approximation = FALSE,
                  D = 1)
fc1 <- forecast(md1, h = h1)
accuracy(fc1, test)
##                      ME      RMSE       MAE        MPE     MAPE      MASE
## Training set  -1.586018  98.37274  72.07709 -0.2748132 3.497391 0.6718145
## Test set     198.515290 216.81325 200.60105  7.9783005 8.055568 1.8697577
##                     ACF1 Theil's U
## Training set  0.02180888        NA
## Test set     -0.02214037  0.815383
# ETS
md2 <- ets(train, opt.crit = "mse")
fc2 <- forecast(md2, h = h1)
accuracy(fc2, test)
##                      ME      RMSE       MAE        MPE     MAPE      MASE
## Training set   4.530822  99.61901  73.11756 0.07081195 3.561811 0.6815125
## Test set     114.734134 173.88352 155.67014 4.94191827 6.458404 1.4509667
##                    ACF1 Theil's U
## Training set 0.06787102        NA
## Test set     0.41614139 0.6901814
# Neural network time series forecasts
md3 <- nnetar(train, 
              P = 2, # using 2 seasonal lags
              p = 1, # and 1 non-seasonal lags
              repeats = 100)
fc3 <- forecast(md3, h = h1)
accuracy(fc3, test)
##                        ME     RMSE       MAE        MPE     MAPE      MASE
## Training set   0.01423023 119.9402  94.28152 -0.3203614 4.587159 0.8787771
## Test set     212.30940334 237.3941 212.30940  8.1450374 8.145037 1.9788886
##                   ACF1 Theil's U
## Training set 0.3865153        NA
## Test set     0.4343893 0.8083805
# Time series linear regression
md4 <- tslm(train ~ season + trend)
fc4 <- forecast(md4, h = h1)
accuracy(fc4, test)
##                                     ME     RMSE       MAE        MPE
## Training set  -0.000000000000004239567 117.1926  90.05241 -0.3040729
## Test set     224.707145243281871671570 247.8366 229.88827  9.0005014
##                  MAPE      MASE       ACF1 Theil's U
## Training set 4.501471 0.8393584 0.57441653        NA
## Test set     9.192438 2.1427373 0.01462551 0.9237391

We will utlize the test_forecast function to visualize the goodness of fit of each model on both the training and testing partitions:

test_forecast(forecast.obj = fc1, actual = USgas, test = test)
test_forecast(forecast.obj = fc2, actual = USgas, test = test)
test_forecast(forecast.obj = fc3, actual = USgas, test = test)
test_forecast(forecast.obj = fc4, actual = USgas, test = test)

Looking at the results above, we can see that ets model achived the lowest error rate on testing set (both RMSE and MAPE) and therefore we will use this model to forecast the monthly consumption in the next 5 years. We will first retrain the model on all the series and review the residuals:

md2a <- ets(USgas, opt.crit = "mse")
fc2a <- forecast(md2a, h = h2)

plot_forecast(fc2a)

Forecasting with backtesting

We will use the ts_backtesting to train and test multiple models (auto.arima, ets, HoltWinters, nnetar, tbats, from the forecast package, hybridModel from the forecastHybrid package and bsts from the bsts package) over six periods of time (periods = 6). Likewise as we did in the traditional approach above, we will set the testing partition to 12 months (h = h1) and the forecast horizon to 60 months (h = h2)

md5 <- ts_backtesting(ts.obj = USgas,
                      periods = 6, 
                      error = "RMSE",
                      window_size = h1,
                      h = h2,
                      a.arg = list(stepwise = FALSE, 
                                   approximation = FALSE,
                                   D = 1),
                      e.arg = list(opt.crit = "mse"),
                      n.arg = list(P = 2, 
                                   p =1,
                                   repeats = 100),
                      h.arg = list(errorMethod = "RMSE",
                                   verbos = FALSE))
##    Model_Name  avgMAPE    sdMAPE  avgRMSE    sdRMSE
## 1        bsts 6.026667 0.5506965 175.1650 15.623280
## 2         ets 6.721667 0.5984786 176.9167 12.839003
## 3      hybrid 6.845000 0.6088924 188.8433  6.837680
## 4  auto.arima 7.008333 0.8395098 199.2150 13.176969
## 5 HoltWinters 7.308333 0.3264608 204.8283  8.812086
## 6       tbats 7.818333 0.8971380 213.9417 19.818474
## 7      nnetar 7.198333 0.6899106 220.0450 10.666534
md5$summary_plot

The main advantage the backtesting approach, over the traditional approach, is that it provides an overview of the performance of each model overtime. This allow you to identify, in additional to accuracy, the stability of the model’s performance overtime. Looking at the summary plot above, you can notice that:

  • The nnetar model is the most stable model, as the range of its RMSE is fairly small.
  • Yet, on average, the auto.arima model achived the lowest RMSE and MAPE on the testing partitions (since we defined the model selection critirion as RMSE, the function select this forecasting approach)
  • You may also consider the bsts or the ets models, as their error consitenly dropping overtime

[1] U.S. Bureau of Transportation Statistics, Natural Gas Consumption [NATURALGAS], retrieved from FRED, Federal Reserve Bank of St. Louis; https://fred.stlouisfed.org/series/NATURALGAS, January 7, 2018.